from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect
from .models import BookInstance, Book, Author, Genre, Language
from datetime import timedelta
from .forms import RenewBookForm, BookForm
from django.views import generic

# Create your views here.

def index(request):
    """首页视图"""
    # 生成一些主要对象的计数
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()
    num_instances_available = BookInstance.objects.filter(status='a').count()
    num_authors = Author.objects.count()
    
    # 获取一些热门图书和作者
    books = Book.objects.all()[:5]  # 最新的5本书
    authors = Author.objects.order_by('-id')[:5]   # 最新的5位作者

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
        'books': books,
        'authors': authors,
    }
    return render(request, 'index.html', context=context)

@login_required
def my_borrowed(request):
    borrowed_books = BookInstance.objects.filter(borrower=request.user, status='o').order_by('due_back')
    context = {
        'borrowed_books': borrowed_books,
    }
    return render(request, 'catalog/my_borrowed.html', context)

# 作者列表视图
def author_list(request):
    authors = Author.objects.all()
    context = { 'authors': authors }
    return render(request, 'catalog/author_list.html', context)

# 作者详情视图
def author_detail(request, pk):
    author = get_object_or_404(Author, pk=pk)
    context = { 'author': author }
    return render(request, 'catalog/author_detail.html', context)

# 作者创建视图（基于类）
class AuthorCreate(LoginRequiredMixin, CreateView):
    model = Author
    fields = ('name', 'bio')
    template_name = 'catalog/author_form.html'

# 作者更新视图（基于类）
class AuthorUpdate(LoginRequiredMixin, UpdateView):
    model = Author
    fields = ('name', 'bio')
    template_name = 'catalog/author_form.html'

# 作者删除视图（基于类）
class AuthorDelete(LoginRequiredMixin, DeleteView):
    model = Author
    success_url = reverse_lazy('author-list')
    template_name = 'catalog/author_confirm_delete.html'

# 图书续借视图（仅限登录用户）
@login_required
def renew_book_librarian(request, pk):
    bookinst = get_object_or_404(BookInstance, pk=pk)
    if bookinst.borrower == request.user:
        # 续借：将归还日期延长 30 天
        bookinst.renew(bookinst.due_back + timedelta(days=30))
        return HttpResponseRedirect(reverse('my-borrowed'))
    else:
        return HttpResponseRedirect(reverse('my-borrowed'))

class BookCreate(PermissionRequiredMixin, CreateView):
    model = Book
    form_class = BookForm
    permission_required = 'catalog.add_book'
    template_name = 'catalog/book_form.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = '添加新书'
        return context

class BookUpdate(PermissionRequiredMixin, UpdateView):
    model = Book
    form_class = BookForm
    permission_required = 'catalog.change_book'
    template_name = 'catalog/book_form.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = '编辑图书'
        return context

class BookDelete(PermissionRequiredMixin, DeleteView):
    model = Book
    permission_required = 'catalog.delete_book'
    success_url = reverse_lazy('books')
    template_name = 'catalog/book_confirm_delete.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = '删除图书'
        return context

class BookListView(generic.ListView):
    """图书列表视图"""
    model = Book
    template_name = 'catalog/book_list.html'
    paginate_by = 10

class BookDetailView(generic.DetailView):
    """图书详情视图"""
    model = Book
    template_name = 'catalog/book_detail.html'

class AuthorListView(generic.ListView):
    """作者列表视图"""
    model = Author
    template_name = 'catalog/author_list.html'
    paginate_by = 10

class AuthorDetailView(generic.DetailView):
    """作者详情视图"""
    model = Author
    template_name = 'catalog/author_detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 获取该作者的所有图书
        author = self.get_object()
        context['books'] = Book.objects.filter(author=author)
        return context

class LoanedBooksByUserListView(LoginRequiredMixin, generic.ListView):
    """当前用户借阅的图书视图"""
    model = BookInstance
    template_name = 'catalog/bookinstance_list_borrowed_user.html'
    paginate_by = 10

    def get_queryset(self):
        return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')